<template>
    <div class="editor">
        <!-- 头部 -->
        <div class="header">
            <div class="left" :style="{width: width - 32 * 2 - 4 * 7 + 'px'}">
                <a-button type="text" @click="toHome()">
                    <template #icon>
                        <icon-left/>
                    </template>
                </a-button>
                <a-input v-model="title" placeholder="请输入文章标题" allow-clear :style="{marginLeft: '7px', width: width - 3 * 32 - 4 * 7 + 'px'}"/>
            </div>
            <a-button-group type="primary">
                <a-button @click="save()" style="margin-right: 7px">
                    <template #icon>
                        <icon-save />
                    </template>
                </a-button>
                <a-button @click="extra.visible = true">
                    <template #icon>
                        <icon-settings/>
                    </template>
                </a-button>
            </a-button-group>
        </div>
        <!-- 编辑区 -->
        <div class="container">
            <markdown-editor v-model="content"/>
        </div>
        <!-- 额外信息 -->
        <a-drawer v-model:visible="extra.visible" title="额外信息" :width="300" :footer="false">
            <a-form :model="extra" layout="vertical">
                <a-form-item label="来源">
                    <a-input v-model="extra.source" :max-length="32"/>
                    <template #help>
                        最大32个字
                    </template>
                </a-form-item>
                <a-form-item label="来源链接">
                    <a-input v-model="base.sourceUrl" :max-length="255"/>
                </a-form-item>
                <a-form-item label="分类">
                    <a-select v-model="extra.categoryId" placeholder="请选择分类">
                        <a-option v-for="category in categories" :value="category.id">{{ category.name }}</a-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="标签">
                    <a-select v-model="extra.tags" placeholder="请输入标签" multiple scrollbar allow-clear allow-search
                              allow-create>
                        <a-option v-for="tag in articleTags" :value="tag">{{ tag }}</a-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="描述">
                    <a-textarea v-model="extra.description" :auto-size="{minRows: 4}"
                                placeholder="请输入描述，不能超过64个字"
                                allow-clear :max-length="64" show-word-limit/>
                </a-form-item>
            </a-form>
        </a-drawer>
    </div>
</template>
<script lang="ts">
import {defineComponent} from "vue";
import {mapState} from "pinia";
import {useGlobalStore} from "@/store/GlobalStore";
import {useArticleStore} from "@/store/db/ArticleStore";
import {useCategoryStore} from "@/store/db/CategoryStore";
import MessageUtil from "@/utils/MessageUtil";
import LocalNameEnum from "@/enumeration/LocalNameEnum";
import {ArticleSource} from "@/entity/article";
import MarkdownEditor from "@/components/markdown-editor/index.vue";

export default defineComponent({
    name: 'editor',
    components: {MarkdownEditor},
    data: () => ({
        id: 0,
        title: '',
        content: '',
        base: {
            sourceUrl: ''
        },
        extra: {
            visible: false,
            tags: new Array<string>(),
            categoryId: undefined as number | undefined,
            description: '',
            createTime: '' as Date | string,
            source: ''
        },
    }),
    computed: {
        ...mapState(useGlobalStore, ['width', 'isDark']),
        ...mapState(useArticleStore, ['articleTags']),
        ...mapState(useCategoryStore, ['categories']),
    },
    created() {
    },
    mounted() {
        this.init()
                .then(() => {
                    const extra = sessionStorage.getItem('extra');
                    sessionStorage.removeItem('extra');
                    if (extra) {
                        this.content = extra;
                    }
                });
    },
    methods: {
        async init() {
            const id = this.$route.params.id as string;
            if (id !== '0') {
                this.id = parseInt(id);
                const articleIndex = useArticleStore().articleMap.get(this.id);
                if (!articleIndex) {
                    MessageUtil.error(`文章【${id}】未找到，请刷新后重试！`);
                    return;
                }
                this.extra = {
                    visible: false,
                    tags: articleIndex.tags,
                    categoryId: articleIndex.categoryId || undefined,
                    description: articleIndex.description,
                    createTime: articleIndex.createTime,
                    source: articleIndex.source
                }
                this.title = articleIndex.name;
                // 基础信息
                const baseWrap = await utools.db.promises.get(LocalNameEnum.ARTICLE_BASE + id);
                if (baseWrap) {
                    this.base = Object.assign(this.base, baseWrap.value);
                }
                // 内容
                const contentWrap = await utools.db.promises.get(LocalNameEnum.ARTICLE_CONTENT + id);
                if (contentWrap) {
                    this.content = (contentWrap.value as ArticleSource).content
                }
            }
        },
        toHome() {
            this.$router.back();
        },
        save() {
            if (this.id === 0) {
                useArticleStore().add({
                    name: this.title,
                    description: this.extra.description,
                    tags: this.extra.tags,
                    categoryId: this.extra.categoryId || null,
                    source: this.extra.source
                }, this.base, this.content)
                        .then(id => {
                            this.id = id;
                            MessageUtil.success("保存文章成功");
                            this.$router.push("/home");
                        })
                        .catch(e => MessageUtil.error("保存文章失败", e));
            } else {
                useArticleStore().update(this.id, {
                    name: this.title,
                    description: this.extra.description,
                    tags: this.extra.tags,
                    categoryId: this.extra.categoryId || null,
                    source: this.extra.source,
                    createTime: this.extra.createTime
                }, this.base, this.content)
                        .then(() => {
                            MessageUtil.success("保存文章成功");
                            this.$router.push("/home");
                        })
                        .catch(e => MessageUtil.error("保存文章失败", e));
            }
        }
    }
});
</script>
<style lang="less">
@import url(./index.less);
</style>
